import axios from 'axios'
import qs from 'qs'
import store from '@/store/index'
import { Message } from 'element-ui'

/* 定义一个基础的请求条件 */
const request = axios.create({
    baseURL: process.env.VUE_APP_BASE_API_ROOT_URL, //   基础的请求前缀
    timeout: 30000 // 请求超时时间
})

/* 开始实现请求 request的拦截器 */
request.interceptors.request.use(
    request => {
        if (request.method && 'GET' === request.method.toLocaleUpperCase()) {
            request.headers['Content-Type'] = 'application/x-www-form-urlencoded'
            if (request.params == undefined) {
                request.params = {}
            }
            if (store.getters['user/isLogin']) {
                request.headers['Authorization'] = store.state.user.token
            }
            request.params = qs.stringify(request.params)
        } else {
            /* POST 、PUT、DELETE方法走这里*/
            request.headers['Content-Type'] = 'application/json'
            if (request.data == undefined) {
                request.data = {}
            }
            if (store.getters['user/isLogin']) {
                request.headers['Authorization'] = store.state.user.token
            }
        }
        return request
    }
)

/* 开始实现请求 response 的拦截器 */
request.interceptors.response.use(
    response => {
        const res = response.data
        if (res.code === 200) {
            return Promise.resolve(res)
        } else if (res.code === 401) {
            Message.error({
                showClose: true,
                message: '对不起，您当前账号无权限操作',
                type: 'error'
            })
            return Promise.reject(res)
        } else {
            Message.error({
                showClose: true,
                message: res.msg,
                type: 'error'
            })
            return Promise.reject(res)
        }
    },
    error => {
        Message.error({
            showClose: true,
            message: '网络请求异常，请稍后重试!',
            type: 'error'
        })
        return Promise.reject(error)
    }
)

/* 暴露接口 */
export default request
